// UI系统模块

class UIManager {
    constructor() {
        this.elements = {};
        this.gameState = {
            score: 0,
            highScore: 0,
            combo: 0,
            maxLevel: 1,
            isGameOver: false,
            isPaused: false,
            gameMode: 'classic'
        };
        
        this.powerUps = {
            bomb: 3,
            magnet: 2,
            pause: 1
        };
        
        this.initElements();
        this.setupEventListeners();
        this.loadGameData();
    }

    // 初始化UI元素
    initElements() {
        this.elements = {
            // 分数显示
            score: document.getElementById('score'),
            highScore: document.getElementById('highScore'),
            combo: document.getElementById('combo'),
            maxLevel: document.getElementById('maxLevel'),
            
            // 下一个球预览
            nextBallPreview: document.getElementById('nextBallPreview'),
            
            // 游戏遮罩
            gameOverlay: document.getElementById('gameOverlay'),
            overlayTitle: document.getElementById('overlayTitle'),
            overlayMessage: document.getElementById('overlayMessage'),
            startButton: document.getElementById('startButton'),
            restartButton: document.getElementById('restartButton'),
            
            // 道具按钮
            bombBtn: document.getElementById('bombBtn'),
            magnetBtn: document.getElementById('magnetBtn'),
            pauseBtn: document.getElementById('pauseBtn'),
            
            // 设置菜单
            settingsMenu: document.getElementById('settingsMenu'),
            settingsBtn: document.getElementById('settingsBtn'),
            closeSettings: document.getElementById('closeSettings'),
            soundToggle: document.getElementById('soundToggle'),
            vibrationToggle: document.getElementById('vibrationToggle'),
            gameModeSelect: document.getElementById('gameModeSelect'),
            
            // 底部按钮
            helpBtn: document.getElementById('helpBtn'),
            pauseGameBtn: document.getElementById('pauseGameBtn')
        };
    }

    // 设置事件监听器
    setupEventListeners() {
        // 游戏开始/重启按钮
        this.elements.startButton?.addEventListener('click', () => {
            this.onStartGame && this.onStartGame();
            Utils.playSound('click');
        });
        
        this.elements.restartButton?.addEventListener('click', () => {
            this.onRestartGame && this.onRestartGame();
            Utils.playSound('click');
        });
        
        // 道具按钮
        this.elements.bombBtn?.addEventListener('click', () => {
            this.usePowerUp('bomb');
        });
        
        this.elements.magnetBtn?.addEventListener('click', () => {
            this.usePowerUp('magnet');
        });
        
        this.elements.pauseBtn?.addEventListener('click', () => {
            this.usePowerUp('pause');
        });
        
        // 设置菜单
        this.elements.settingsBtn?.addEventListener('click', () => {
            this.showSettings();
        });
        
        this.elements.closeSettings?.addEventListener('click', () => {
            this.hideSettings();
        });
        
        // 设置选项
        this.elements.soundToggle?.addEventListener('change', (e) => {
            this.toggleSound(e.target.checked);
        });
        
        this.elements.vibrationToggle?.addEventListener('change', (e) => {
            this.toggleVibration(e.target.checked);
        });
        
        this.elements.gameModeSelect?.addEventListener('change', (e) => {
            this.changeGameMode(e.target.value);
        });
        
        // 其他按钮
        this.elements.helpBtn?.addEventListener('click', () => {
            this.showHelp();
        });
        
        this.elements.pauseGameBtn?.addEventListener('click', () => {
            this.togglePause();
        });
        
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            this.handleKeyPress(e);
        });
    }

    // 更新分数显示
    updateScore(score) {
        this.gameState.score = score;
        if (this.elements.score) {
            this.elements.score.textContent = Utils.formatScore(score);
        }
        
        // 更新最高分
        if (score > this.gameState.highScore) {
            this.gameState.highScore = score;
            if (this.elements.highScore) {
                this.elements.highScore.textContent = Utils.formatScore(score);
            }
            this.saveGameData();
        }
    }

    // 更新连击数
    updateCombo(combo) {
        this.gameState.combo = combo;
        if (this.elements.combo) {
            this.elements.combo.textContent = combo;
            
            // 连击特效
            if (combo > 1) {
                this.elements.combo.parentElement.classList.add('combo-highlight');
                setTimeout(() => {
                    this.elements.combo.parentElement.classList.remove('combo-highlight');
                }, 500);
            }
        }
    }

    // 更新最高级球
    updateMaxLevel(level) {
        this.gameState.maxLevel = Math.max(this.gameState.maxLevel, level);
        if (this.elements.maxLevel) {
            this.elements.maxLevel.textContent = this.gameState.maxLevel;
        }
    }

    // 更新下一个球预览
    updateNextBall(level) {
        if (this.elements.nextBallPreview) {
            const color = Utils.getBallColor(level);
            this.elements.nextBallPreview.style.background = color;
            this.elements.nextBallPreview.className = `ball-preview ball-level-${level}`;
        }
    }

    // 显示游戏开始界面
    showStartScreen() {
        this.showOverlay('游戏开始', '点击罐子上方生成球体，合成更高级的球！', 'start');
    }

    // 显示游戏结束界面
    showGameOverScreen() {
        const message = `游戏结束！\n最终分数: ${Utils.formatScore(this.gameState.score)}\n最高级球: ${this.gameState.maxLevel}级`;
        this.showOverlay('游戏结束', message, 'gameOver');
        
        // 播放游戏结束音效
        Utils.playSound('gameOver');
        Utils.vibrate(200);
    }

    // 显示遮罩层
    showOverlay(title, message, type) {
        if (this.elements.gameOverlay) {
            this.elements.overlayTitle.textContent = title;
            this.elements.overlayMessage.textContent = message;
            
            // 显示对应按钮
            if (type === 'start') {
                this.elements.startButton.classList.remove('hidden');
                this.elements.restartButton.classList.add('hidden');
            } else if (type === 'gameOver') {
                this.elements.startButton.classList.add('hidden');
                this.elements.restartButton.classList.remove('hidden');
            }
            
            this.elements.gameOverlay.classList.remove('hidden');
            this.elements.gameOverlay.classList.add('fade-in');
        }
    }

    // 隐藏遮罩层
    hideOverlay() {
        if (this.elements.gameOverlay) {
            this.elements.gameOverlay.classList.add('fade-out');
            setTimeout(() => {
                this.elements.gameOverlay.classList.add('hidden');
                this.elements.gameOverlay.classList.remove('fade-in', 'fade-out');
            }, 300);
        }
    }

    // 使用道具
    usePowerUp(type) {
        if (this.powerUps[type] <= 0) {
            this.showMessage('道具已用完！', 'warning');
            return false;
        }
        
        this.powerUps[type]--;
        this.updatePowerUpDisplay(type);
        
        // 触发道具使用事件
        this.onPowerUpUsed && this.onPowerUpUsed(type);
        
        Utils.playSound('powerup');
        Utils.vibrate(50);
        
        return true;
    }

    // 更新道具显示
    updatePowerUpDisplay(type) {
        const button = this.elements[type + 'Btn'];
        if (button) {
            const countElement = button.querySelector('.count');
            if (countElement) {
                countElement.textContent = this.powerUps[type];
            }
            
            // 如果用完了，禁用按钮
            if (this.powerUps[type] <= 0) {
                button.disabled = true;
                button.classList.add('disabled');
            }
        }
    }

    // 重置道具
    resetPowerUps() {
        this.powerUps = {
            bomb: 3,
            magnet: 2,
            pause: 1
        };
        
        // 更新显示
        Object.keys(this.powerUps).forEach(type => {
            this.updatePowerUpDisplay(type);
            const button = this.elements[type + 'Btn'];
            if (button) {
                button.disabled = false;
                button.classList.remove('disabled');
            }
        });
    }

    // 显示设置菜单
    showSettings() {
        if (this.elements.settingsMenu) {
            this.elements.settingsMenu.classList.remove('hidden');
            this.elements.settingsMenu.classList.add('fade-in');
        }
        Utils.playSound('click');
    }

    // 隐藏设置菜单
    hideSettings() {
        if (this.elements.settingsMenu) {
            this.elements.settingsMenu.classList.add('fade-out');
            setTimeout(() => {
                this.elements.settingsMenu.classList.add('hidden');
                this.elements.settingsMenu.classList.remove('fade-in', 'fade-out');
            }, 300);
        }
        Utils.playSound('click');
    }

    // 切换音效
    toggleSound(enabled) {
        if (window.AudioManager) {
            window.AudioManager.setEnabled(enabled);
        }
        Utils.saveToStorage('soundEnabled', enabled);
    }

    // 切换震动
    toggleVibration(enabled) {
        Utils.saveToStorage('vibrationEnabled', enabled);
    }

    // 改变游戏模式
    changeGameMode(mode) {
        this.gameState.gameMode = mode;
        this.onGameModeChanged && this.onGameModeChanged(mode);
        Utils.saveToStorage('gameMode', mode);
    }

    // 显示帮助
    showHelp() {
        const helpText = `游戏规则：\n\n1. 点击罐子上方投放球体\n2. 相同等级的球体碰撞后合成\n3. 球体超过红线游戏结束\n4. 合成更高级球体获得分数\n\n道具说明：\n💣 炸弹：清除指定区域球体\n🧲 磁铁：吸引相同等级球体\n⏸️ 暂停：暂停球体下落`;
        
        alert(helpText);
        Utils.playSound('click');
    }

    // 切换暂停
    togglePause() {
        this.gameState.isPaused = !this.gameState.isPaused;
        this.onPauseToggled && this.onPauseToggled(this.gameState.isPaused);
        
        // 更新按钮文字
        if (this.elements.pauseGameBtn) {
            this.elements.pauseGameBtn.textContent = this.gameState.isPaused ? '▶️ 继续' : '⏸️ 暂停';
        }
        
        Utils.playSound('click');
    }

    // 处理键盘按键
    handleKeyPress(event) {
        switch(event.code) {
            case 'Space':
                event.preventDefault();
                this.togglePause();
                break;
            case 'KeyR':
                if (event.ctrlKey) {
                    event.preventDefault();
                    this.onRestartGame && this.onRestartGame();
                }
                break;
            case 'Escape':
                if (!this.elements.settingsMenu.classList.contains('hidden')) {
                    this.hideSettings();
                }
                break;
        }
    }

    // 显示消息提示
    showMessage(message, type = 'info', duration = 2000) {
        const messageElement = document.createElement('div');
        messageElement.className = `game-message ${type}`;
        messageElement.textContent = message;
        messageElement.style.cssText = `
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: ${type === 'warning' ? '#ff4757' : '#2ed573'};
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            z-index: 1000;
            font-weight: bold;
            animation: slideDown 0.3s ease-out;
        `;
        
        document.body.appendChild(messageElement);
        
        setTimeout(() => {
            messageElement.style.animation = 'slideUp 0.3s ease-in';
            setTimeout(() => {
                if (messageElement.parentNode) {
                    messageElement.parentNode.removeChild(messageElement);
                }
            }, 300);
        }, duration);
    }

    // 保存游戏数据
    saveGameData() {
        const gameData = {
            highScore: this.gameState.highScore,
            soundEnabled: this.elements.soundToggle?.checked ?? true,
            vibrationEnabled: this.elements.vibrationToggle?.checked ?? true,
            gameMode: this.gameState.gameMode
        };
        
        Utils.saveToStorage('ballGameData', gameData);
    }

    // 加载游戏数据
    loadGameData() {
        const gameData = Utils.loadFromStorage('ballGameData', {});
        
        // 加载最高分
        if (gameData.highScore) {
            this.gameState.highScore = gameData.highScore;
            if (this.elements.highScore) {
                this.elements.highScore.textContent = Utils.formatScore(gameData.highScore);
            }
        }
        
        // 加载设置
        if (this.elements.soundToggle && gameData.soundEnabled !== undefined) {
            this.elements.soundToggle.checked = gameData.soundEnabled;
            this.toggleSound(gameData.soundEnabled);
        }
        
        if (this.elements.vibrationToggle && gameData.vibrationEnabled !== undefined) {
            this.elements.vibrationToggle.checked = gameData.vibrationEnabled;
        }
        
        if (this.elements.gameModeSelect && gameData.gameMode) {
            this.elements.gameModeSelect.value = gameData.gameMode;
            this.gameState.gameMode = gameData.gameMode;
        }
    }

    // 重置游戏状态
    resetGameState() {
        this.gameState.score = 0;
        this.gameState.combo = 0;
        this.gameState.maxLevel = 1;
        this.gameState.isGameOver = false;
        this.gameState.isPaused = false;
        
        // 更新显示
        this.updateScore(0);
        this.updateCombo(0);
        this.updateMaxLevel(1);
        this.resetPowerUps();
        
        // 重置暂停按钮
        if (this.elements.pauseGameBtn) {
            this.elements.pauseGameBtn.textContent = '⏸️ 暂停';
        }
    }

    // 设置事件回调
    setEventCallbacks(callbacks) {
        this.onStartGame = callbacks.onStartGame;
        this.onRestartGame = callbacks.onRestartGame;
        this.onPowerUpUsed = callbacks.onPowerUpUsed;
        this.onPauseToggled = callbacks.onPauseToggled;
        this.onGameModeChanged = callbacks.onGameModeChanged;
    }

    // 获取游戏状态
    getGameState() {
        return { ...this.gameState };
    }
}

// 导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = UIManager;
}